package chapter21.others;

import chapter21.section3.Accessor;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by lzy
 * Date: 2018/6/7
 */
public class ThreadLocalVariableHolder {
    private static final ThreadLocal<Integer> value = new ThreadLocal<Integer>() {
        private final Random rand = new Random(47);

        @Override
        protected synchronized Integer initialValue() {
            return rand.nextInt(10000);
        }
    };

    private static final ThreadLocal<Integer> container = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return super.initialValue();
        }

        @Override
        public Integer get() {
            return super.get();
        }

        @Override
        public void set(Integer value) {
            super.set(value);
        }

        @Override
        public void remove() {
            super.remove();
        }
    };

    public static void increment() {
        value.set(value.get() + 1);
    }

    public static int get(){
        return value.get();
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            exec.execute(new Accessor(i));
        }
        TimeUnit.SECONDS.sleep(3);
        exec.shutdownNow();
    }
}
